#include <stdio.h>
#include <stdlib.h>

int main (int argc, char *argv[])
{
    FILE *fi, *fo;
    char *cp;
    int c;

    if (argc != 4) {
        printf ("USAGE: a.out <key> <input plaintext file> <output ciphertext file>\n");
        return EXIT_FAILURE;
    }

    cp = argv[1];
    if ( *cp == '\0') {
        printf ("ERROR: key is NULL\n");
        return EXIT_FAILURE;
    }

    if ((fi = fopen(argv[2], "rb")) == NULL) {
        printf ("ERROR: Unable to open input plaintext file = %s\n", argv[2]);
        return EXIT_FAILURE;
    }

    if ((fo = fopen(argv[3], "wb")) == NULL) {
        printf ("ERROR: Unabel to open output ciphertext file = %s\n", argv[3]);
        return EXIT_FAILURE;
    }

    while ((c = getc(fi)) != EOF) {
        if (!*cp) cp = argv[1];
        c ^= *(cp++);
        putc(c,fo);
    }
    fclose(fo);
    fclose(fi);

    return EXIT_SUCCESS;
}
